import { createRouter, createWebHistory } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { ElMessage } from 'element-plus'
//导入组件
import LoginVue from '@/views/Login.vue'
import LayoutVue from '@/views/Layout.vue'
import IndexVue from '@/views/Index.vue'
import UserManageVue from '@/views/user/UserManage.vue'
import HouseholderManageVue from '@/views/user/HouseholderManage.vue'
import PersonAccessRecordsVue from '@/views/user/PersonAccessRecords.vue'
import CarManageVue from '@/views/car/CarManage.vue'
import CarAccessRecordsVue from '@/views/car/CarAccessRecords.vue'
import UserResetPasswordVue from '@/views/userCenter/UserResetPassword.vue'
//定义路由关系
const routes = [
    { path: '/login', component: LoginVue },
    {
        path: '/', component: LayoutVue, redirect: '/index', children: [
            // 主页
            { path: '/index', component: IndexVue },
            // 用户管理
            { path: '/user/userManage', component: UserManageVue },
            //住户管理
            { path: '/user/householderManage', component: HouseholderManageVue },
            //人员出入记录
            { path: '/user/personAccessRecords', component: PersonAccessRecordsVue },
            //车辆管理
            { path: '/car/carManage', component: CarManageVue },
            //车辆出入记录
            { path: '/car/carAccessRecordsVue', component: CarAccessRecordsVue },

            //个人中心
            //重置密码
            { path: '/userCenter/resetPassword', component: UserResetPasswordVue }
        ]
    }
]

//创建路由
const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

// 添加全局前置守卫
router.beforeEach(async (to, from, next) => {
    const tokenStore = useTokenStore()
    const token = tokenStore.token

    // 如果是前往登录页面，则直接放行
    if (to.path === '/login') {
        next()
    } else {
        // 如果没有token，则重定向到登录页面
        if (!token) {
            ElMessage.error('请先登录！')
            next('/login')
        } else {
            // 如果有token，则允许继续导航
            next()
        }
    }
})

//导出路由
export default router